<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('员工名称')" prop="userId">
            <UserSelect v-model="form.userId" :placeholder="$t('员工名称')" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('所属部门')" prop="deptId">
            <tree-select
              v-model="form.deptId"
              :default-expand-all="true"
              :data="initData.deptOptions"
              :placeholder="$t('请选择')"
              node-key="id"
              disabled
            >
              <label
                slot="option-label"
                slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }"
                :class="labelClassName"
              >
                {{ $t(node.label) }}
                <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
              </label>
            </tree-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('填报时间')" prop="fillingTime">
            <el-date-picker
              v-model="form.fillingTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('填报时间')"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 明细 -->
      <div style="margin-top:15px;">
        <div class="area-header">
          <span class="area-header-title">{{ $t('股票明细') }} </span> <span style="color:red">{{
            $t('(预计交易时间超过1周则无需填写)')
          }}</span>
        </div>
        <div>
          <el-table
            :data="form.riskSharesStaffs"
            border
            class="nowrapTable formTable"
          >
            <el-table-column :label="$t('序号')" align="center" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('股票名称')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('股票名称') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  :prop="'riskSharesStaffs.' + scope.$index + '.stockName'"
                  :rules="riskSharesStaffsRules.stockName"
                >
                  <el-input v-model="scope.row.stockName" :placeholder="$t('股票名称')" show-word-limit maxlength="100" type="textarea" :autosize="{ minRows: 1, maxRows: 10}" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('股票代码')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('股票代码') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  :prop="'riskSharesStaffs.' + scope.$index + '.stockCode'"
                  :rules="riskSharesStaffsRules.stockCode"
                >
                  <el-input v-model="scope.row.stockCode" :placeholder="$t('股票代码')" show-word-limit maxlength="50" type="textarea" :autosize="{ minRows: 1, maxRows: 10}" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('预计交易时间')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('预计交易时间') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  :prop="'riskSharesStaffs.' + scope.$index + '.estimatedTime'"
                  :rules="riskSharesStaffsRules.estimatedTime"
                >
                  <el-date-picker
                    v-model="scope.row.estimatedTime"
                    clearable
                    style="width: 200px"
                    type="date"
                    value-format="yyyy-MM-dd"
                    :placeholder="$t('预计交易时间')"
                    :picker-options="pickerOptions"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="form.id === undefined" :label="$t('操作')" align="center" width="60px">
              <template slot-scope="scope">
                <el-button size="small" type="text" icon="el-icon-delete" @click="delInfo(scope.$index, scope.row)" />
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="form.id === undefined" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addInfo">{{ $t('添加') }}</el-button>
        </div>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn v-show="!btnHide" has-permi="risk:staff" />
    </div>
  </div>
</template>

<script>
import {
  saveRiskSharesStaff,
  getRiskSharesStaff,
  delRiskSharesStaff
} from '@/api/deal/risk/shares/staff/riskSharesStaff.js'
import { treeselect } from '@/api/system/dept'
import TreeSelect from '@/components/TreeSelect'
import { getUser } from '@/api/system/user'

export default {
  components: { TreeSelect },
  data() {
    return {
      userId: this.$store.state.user.userId,
      // 表单参数
      form: {
        id: undefined,
        riskSharesStaffs: []
      },
      btnHide: false,
      // 遮罩层
      loading: false,
      // 表单校验
      rules: {},
      riskSharesStaffsRules: {
        stockName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        stockCode: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        estimatedTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      initData: {
        deptOptions: []
      },
      riskSharesStaffsHide: false,
      pickerOptions: {
        disabledDate(time) {
          var dateTime = new Date()
          dateTime = dateTime.setDate(dateTime.getDate() - 1)
          dateTime = new Date(dateTime)
          const curDate = (dateTime).getTime()
          const three = 7 * 24 * 3600 * 1000
          const threeMonths = curDate + three
          return time.getTime() <= curDate || time.getTime() > threeMonths
        }
      }
    }
  },
  created() {
    this.initDataMethod()
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      if (data != null && data.id !== undefined) {
        this.btnHide = true
        getRiskSharesStaff(data.id).then(response => {
          this.form = response.data
          this.loading = false
        })
      } else {
        this.reset()
        this.btnHide = false
        this.loading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        userId: this.userId,
        deptId: undefined,
        fillingTime: new Date(),
        remark: undefined
      }
      this.resetForm('form')
      getUser(this.userId).then(res => {
        this.$set(this.form, 'deptId', res.data.deptId)
      })
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      if (this.form.riskSharesStaffs === undefined || this.form.riskSharesStaffs.length < 1) {
        this.msgError(this.$t('请至少添加一条股票明细'))
        return
      }
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          saveRiskSharesStaff(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.closeForm()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      })
    },
    // 初始化数据
    initDataMethod() {
      treeselect().then(response => {
        this.initData.deptOptions = response.data
      })
    },
    addInfo() {
      const row = {
        stockName: '',
        stockCode: '',
        distributionPrincipal: '',
        estimatedTime: ''
      }
      if (!(this.form.riskSharesStaffs instanceof Array)) {
        this.$set(this.form, 'riskSharesStaffs', [])
      }
      this.$nextTick(() => {
        this.form.riskSharesStaffs.push(row)
      })
    },
    // 删除明细
    delInfo(index, row) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(function() {
          return delRiskSharesStaff(id)
        }).then(() => {
          this.form.riskSharesStaffs.splice(index, 1)
          this.calculationMoney()
          return this.msgSuccess(this.$t('删除成功'))
        }).catch(function() {
        })
      } else {
        this.form.riskSharesStaffs.splice(index, 1)
      }
    }
  }

}
</script>
